import axios from 'axios'
import { Message } from 'element-ui'
import router from '../router'
// import { JSEncrypt } from 'jsencrypt'
import { JSEncrypt } from 'encryptlong'

// import Cookies from 'js-cookie'

axios.defaults.withCredentials = true
const service = axios.create({
  baseURL: process.env.PROGOO_GATE_WATER,
  timeout: 60000
})

// request拦截器
service.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    // config.headers['Set-Cookie'] = 'SameSite=None;Secure'
    let token = localStorage.getItem('token')
    if(token && token !== '') {
      config.headers['x-auth-token'] = token
      // config.headers['Authorization'] = token
    }
    config.url = encodeURI(config.url)
    /**
     * RSA加密 create by LDC on 20220316
     */
    let key ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCts3zzefN1d+SCafaCa2ihtJ4xMcKNOVB+W6CRNLOaAFTTbQT16/R4vrUenXbZ3OAGTpGT37tzgGCSzLeqTQlUJKA/w3AB4T72YG9iXBwyEkX/WgR/R0WCARtvQTF9YFIgnHVuQCnNH5kYvcGxWcNwG+lYkSIMh+FQAwZ1TZxLmwIDAQAB"
    if(config.method == 'get') {
      if(config.params) {
        if(config.params.needRSA && config.params.needRSA === '1') {
          // 加密数据
          let encryptor = new JSEncrypt();
          // 设置公钥
          encryptor.setPublicKey(key);
          let pa = JSON.stringify(config.params)
          config.params = encryptor.encryptLong(pa);
        }
      }
    }else {
      if(config.data) {
        if(config.data.needRSA && config.data.needRSA === '1') {
          // 加密数据
          let encryptor = new JSEncrypt();
          // 设置公钥
          encryptor.setPublicKey(key);
          let da = JSON.stringify(config.data)
          config.data = encryptor.encryptLong(da);
        }
      }
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  response => {
    if(response.data && response.data.code !== 200 && response.data.code !== 400){
      Message({
        message: '登录异常，请重新登录',
        type: 'error'
      })
      router.push({ name: 'login' })
    }
    return response
  },
  error => {
    let response = error.response
    if (!response) {
      // router.push({ name: 'login' })
      return Promise.reject(error)
    } else {
      let code = response.status
      if (code === 401 || code === 403) {
        Message({
          message: 'token异常，请重新登录',
          type: 'error'
        })
        router.push({ name: 'login' })
      } else if (code === 400) {
        Message({
          message: response.data.message,
          type: 'error'
        })
        return Promise.reject(response.data)
      } else if (code === 500) {
        router.push({ path: '/500' })
      } else {
        return Promise.reject(error)
      }
    }
  }
)
export default service
